/* eslint-disable eqeqeq */
import { DatePicker2, Dialog, Field, Form, Input, Select, ResponsiveGrid, Button, Icon, Drawer } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable, toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import UploadPanel from '@/components/UploadPanel';
import { ENUMS, toSelectDataSource, column, TitleGrid, model } from '../pages/Refund/stores/definitions';
import dayjs from 'dayjs';
import AttachmentForm from './AttachmentForm';
import TauTable from '@/components/TauTable';
import DrawerFooter from '@/components/DrawerFooter';


const { Cell } = ResponsiveGrid;

export const PayDrawer = observer(({ visible, byMethod, onClose, onOk, modal, ...props }) => {
  const [data] = useState(() => observable({ method: byMethod !== undefined ? byMethod : 0, payTime: '', payRemark: '', attachments: [] }));
  const formField = Field.useField();
  useEffect(() => {
    if (visible) {
      _.assign(data, { method: byMethod !== undefined ? byMethod : 0, payTime: '', payRemark: '', attachments: [] });
    }
  }, [visible]);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(data, name, value);
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    data.payTime = data.payTime && data.payTime.toJSON();
    onOk?.(data);
  };

  if (!visible) return;

  return (
    <Drawer
      style={{ width: 600 }}
      visible={visible}
      {...props}
      // onOk={handleOk}
      closeMode={['close', 'esc']}
      onClose={onClose}
      onCancel={onClose}
    >
      <Form field={formField} value={data} onChange={handleChange} useLabelForErrorMessage>
        {byMethod === undefined &&
          <Form.Item label={t`支付方式`} required name="method">
            <Select style={{ width: '100%' }} hasClear={false} dataSource={toSelectDataSource(ENUMS.selectPayMethod)} value={data.method} />
          </Form.Item>}
        {data.method == 1 &&
          <Form.Item label={t`实际支付时间`} required name="payTime">
            <DatePicker2
              showTime
              format="YYYY-MM-DD HH:mm"
              timePanelProps={{ format: 'HH:mm' }}
              disabledDate={(d) => d.isAfter(dayjs())}
              preset={{ [t`此刻`]: dayjs() }}
              value={data.payTime}
              style={{ width: '100%' }}
            />
          </Form.Item>}
        <Form.Item label={t`支付说明`} required name="payRemark">
          <Input.TextArea value={data.payRemark} />
        </Form.Item>

        <AttachmentPanel refund={data} mode={modal} />

        <DrawerFooter>
          <Form.Item>
            <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
            <Button style={{ marginLeft: 8 }} onClick={onClose}>{t`取消`}</Button>
          </Form.Item>
        </DrawerFooter>
      </Form>
    </Drawer>
  );
});

const AttachmentPanel = observer(({ refund, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'view';

  useEffect(() => {
    if (refund?.attachments?.length) setIdx(0);
  }, [refund?.attachments]);

  const handleAddAttachment = () => {
    if (!refund?.attachments) refund.attachments = [];
    refund.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(refund.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    refund.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid style={{ width: 200, fontWeight: 500, fontSize: 16 }} title={<span>{t`附件`}{mode?.visible !== 'viewRefund' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={11}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(refund?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, model?.attachments[0]),
              column('description', {}, model?.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`refund:${refund.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(refund.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              refund.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              refund.attachments[idx]?.binaryId.splice(refund.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(refund.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});
